﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FormatUtil;
namespace SanitationTcpGw
{
    public class RtDataCache
    {
        static RtDataCache _inst = null;
        public static RtDataCache Instance
        {
            get { return _inst ?? (_inst = new RtDataCache()); }
        }

        public RtDataCache()
        {
            WaitBuffersCache = new Dictionary<string, byte[]>();
        }



        #region 未处理缓冲区

        /// <summary>
        /// 未处理缓冲区
        /// key = socket句柄
        /// </summary>
        private Dictionary<string, byte[]> WaitBuffersCache { get; set; }

        private readonly object _waitBuffersLockObject = new object();

        public byte[] GetWaitBuffers(string connectId)
        {
            lock (_waitBuffersLockObject)
            {
                if (WaitBuffersCache.ContainsKey(connectId))
                    return WaitBuffersCache[connectId];
                else
                {
                    WaitBuffersCache.Add(connectId, null);
                    return null;
                }
            }
        }

        public void AddWaitBuffers(string connectId, byte[] buffers)
        {
            lock (_waitBuffersLockObject)
            {
                WaitBuffersCache[connectId] = buffers;
            }
        }

        /// <summary>
        /// 断开连接清理操作
        /// </summary>
        /// <param name="connectionId"></param>
        public void DisconnectClear(string connectionId)
        {
            lock (_waitBuffersLockObject)
            {
                if (WaitBuffersCache.ContainsKey(connectionId))
                {
                    LogHelp.WriteeLog("DisconnectClear", string.Format("链路断开，清空缓冲区[handle={0}],[length={1}] ", connectionId, WaitBuffersCache[connectionId] == null ? 0 : WaitBuffersCache[connectionId].Length));
                    this.WaitBuffersCache.Remove(connectionId);
                    //GC.Collect();
                }
            }
        }

        #endregion

    }
}
